<template>
	<div class="import">
		<preview-images ref="previewImages" />
		<div class="product-name">{{ productData.name }}</div>
		<el-card class="box-card" v-if="productId != 11804">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold"
					>投保企业（上传营业执照可自动识别企业信息）</span
				>
				<el-checkbox
					v-model="sameAsToubao"
					size="medium"
					style="float: right; padding: 3px 0"
					>被保企业同投保企业
				</el-checkbox>
			</div>
			<el-form
				:model="toubaoForm"
				:rules="rules"
				label-width="130px"
				ref="toubaoForm"
				v-loading="toubaoLoading"
			>
				<el-form-item label="企业名称" prop="customerName" required>
					<el-select
						v-model="toubaoForm.customerName"
						@change="(val) => getToubaoById(val)"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择企业"
					>
						<el-option
							v-for="customer in customerOptions"
							:value="customer.customerId"
							:label="customer.customerName"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="联系人" prop="contactName" required>
					<el-input
						v-model="toubaoForm.contactName"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="统一社会信用代码" prop="certNum" required>
					<el-input
						v-model="toubaoForm.certNum"
						placeholder="请输入统一社会信用代码"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<el-form-item label="手机号码" prop="contactPhone" required>
					<el-input
						v-model="toubaoForm.contactPhone"
						placeholder="请输入手机号码"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="详细地址" prop="address" required>
					<el-input
						v-model="toubaoForm.address"
						placeholder="请输入详细地址"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="营业执照" prop="businessLicense" required>
					<el-upload
						:class="{ 'hide-upload-button': toubaoForm.businessLicense }"
						:before-remove="toubaoBeforeRemove"
						:on-preview="() => onPreview(toubaoForm.businessLicense.url)"
						:limit="0"
						:http-request="handleToubaoUpload"
						:file-list="[toubaoForm.businessLicense].filter(Boolean)"
						list-type="picture-card"
					>
						<i class="el-icon-plus"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="示例">
					<el-image
						style="width: 148px; height: 148px"
						src="https://qtbx.meibaokeji.com.cn/employer/static/2022images/yyzz.png"
						:preview-src-list="[
							'https://qtbx.meibaokeji.com.cn/employer/static/2022images/yyzz.png'
						]"
					>
					</el-image>
				</el-form-item>
				<el-form-item
					v-if="toubaoForm.businessLicense && toubaoForm.contactPhone"
					label="短信验证码"
					prop="code"
				>
					<el-input
						v-model="toubaoForm.code"
						placeholder="请输入短信验证码"
						size="mini"
						class="field"
					></el-input>
				</el-form-item>
				<div style="grid-column: -1/1; text-align: center">
					<el-button
						size="small"
						type="primary"
						@click="sendCode"
						v-if="
							toubaoForm.businessLicense &&
							toubaoForm.contactPhone &&
							!this.toubaoForm.code
						"
						:loading="codeLoading"
						>发送验证码</el-button
					>
					<el-button size="small" type="primary" v-else @click="saveToubao">
						确认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-card class="box-card" v-if="sameAsToubao === false">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold"
					>被保企业（上传营业执照可自动识别企业信息）</span
				>
			</div>
			<el-form
				:model="beibaoForm"
				:rules="rules"
				label-width="130px"
				ref="beibaoForm"
				v-loading="beibaoLoading"
			>
				<el-form-item label="营业执照" prop="businessLicense" required>
					<div style="display: flex; align-items: top; gap: 10px">
						<el-upload
							:class="{ 'hide-upload-button': beibaoForm.businessLicense }"
							:before-remove="beibaoBeforeRemove"
							:on-preview="() => onPreview(beibaoForm.businessLicense.url)"
							:limit="0"
							:http-request="handleBeibaoUpload"
							:file-list="[beibaoForm.businessLicense].filter(Boolean)"
							list-type="text"
						>
							<span class="c-main"><i class="el-icon-plus"></i>点击上传</span>
						</el-upload>
						<!-- <a
							href="https://qtbx.meibaokeji.com.cn/employer/static/2022images/yyzz.png"
							>查看示例</a
						> -->
					</div>
				</el-form-item>
				<el-form-item label="企业名称" prop="customerName" required>
					<el-select
						v-model="beibaoForm.customerName"
						@change="(val) => getBeibaoById(val)"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择企业"
					>
						<el-option
							v-for="customer in customerOptions"
							:value="customer.customerId"
							:label="customer.customerName"
						/>
					</el-select>
				</el-form-item>
				<el-form-item
					label="行业大类"
					prop="premiumMode"
					v-if="productData.premiumMode"
				>
					<el-select
						v-model="beibaoForm.premiumMode"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择行业大类"
					>
						<el-option
							v-for="mode in productData.premiumMode"
							:value="mode.value"
							:label="mode.name"
							:key="mode.value"
						/>
					</el-select>
				</el-form-item>

				<el-form-item label="联系人" prop="contactName" required>
					<el-input
						v-model="beibaoForm.contactName"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="统一社会信用代码" prop="certNum" required>
					<el-input
						v-model="beibaoForm.certNum"
						placeholder="请输入统一社会信用代码"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<el-form-item label="手机号码" prop="contactPhone" required>
					<el-input
						v-model="beibaoForm.contactPhone"
						placeholder="请输入手机号码"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="所在地区" prop="area">
					<xh-address
						:value="beibaoForm.area"
						@value-change="({ value }) => (beibaoForm.area = value)"
					></xh-address>
				</el-form-item>
				<el-form-item label="详细地址" prop="address" required>
					<el-input
						v-model="beibaoForm.address"
						placeholder="请输入详细地址"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<div style="grid-column: -1/1; text-align: center">
					<el-button size="small" type="primary" @click="saveBeibao">
						确认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">保障期限 </span>
			</div>
			<el-form
				:model="qixianForm"
				:rules="qixianRules"
				label-width="130px"
				ref="qixianForm"
				v-loading="qixianLoading"
			>
				<el-form-item label="保单起期" prop="startTime" required>
					<el-date-picker
						v-model="qixianForm.startTime"
						size="mini"
						placeholder="请选择开始时间"
						type="date"
						value-format="yyyy-MM-dd"
						style="width: 100%"
						:picker-options="startDatePickerOptions"
					/>
					<span class="append-fix">00:00:00</span>
				</el-form-item>
				<el-form-item label="保单止期" prop="endTime" required>
					<el-date-picker
						v-model="qixianForm.endTime"
						:readonly="
							!productData.policyType ||
							!!productData.insuranceType ||
							productData.policyType === 4
						"
						size="mini"
						placeholder="请选择结束时间"
						type="date"
						value-format="yyyy-MM-dd"
						style="width: 100%"
					/>
					<span class="append-fix">23:59:59</span>
				</el-form-item>
				<el-form-item label="保单期间" prop="endTime" required>
					<el-input
						v-model="baoxianqijian"
						readonly
						size="mini"
						style="width: 100%"
					>
					</el-input>
				</el-form-item>
				<div style="grid-column: -1/1; text-align: center">
					<el-button size="small" type="primary" @click="saveQixian">
						确 认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-card class="box-card" v-if="showPerson" v-loading="personLoading">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">保障人员</span>
			</div>
			<insure-import
				:productId="productId"
				:start-time="qixianForm.startTime"
				:end-time="qixianForm.endTime"
				@success="onSuccess"
			/>
		</el-card>

		<!-- <div style="margin-block: 20px; text-align: center">
			<el-button @click="save" type="primary" size="medium">保存</el-button>
		</div> -->
	</div>
</template>

<script>
import {
	productDetail,
	createBusiness,
	customerList,
	customerById,
	uploadFile,
	licenseOcr,
	sendSMSCode,
	saveInsure,
	saveBeibao,
	saveQixian,
	save,
	getBusinessById
} from '@/api'
import _ from 'lodash'
import * as REGEXP from '@/const/REGEXP'
import { downloadByResponse } from '@/utils/download'
import { queryCitys, queryAreaByCode } from '@/api/form'
import moment from 'moment'
import XhAddress from '@/components/createCom/XhAddress.vue'
import { start } from 'nprogress'
import { TRUE } from 'sass'
var urlSearchParams = new URLSearchParams(location.search)
var UrlSearch = {}
for (let [key, value] of urlSearchParams.entries()) {
	UrlSearch[key] = value
}
import { transformKey } from '@/utils'
import insureImport from './components/insure-import.vue'
const baoform = {
	customerId: '', // 企业的id
	customerName: '', // 企业名称
	certNum: '', // 统一代码
	area: {},
	address: '', // 详细地址
	contactName: '', // 联系人
	contactPhone: '', // 手机号
	businessLicense: '', // 营业执照
	code: '', // 验证码
	// provinceCode: '',
	cityCode: '',
	regionCode: '',
	// 产品订单的类型 1国寿类 2太保类
	policyType: 1 // 默认国寿类
}
export default {
	data() {
		var that = this

		const startTime = moment().add(1, 'days').format('yyyy-MM-DD')
		return {
			productData: {},
			sameAsToubao: true, // 被保企业同投保企业
			businessId: '',
			toubaoForm: Object.assign({}, baoform),
			beibaoForm: Object.assign({}, baoform),
			toubaoBusinessLicenseFile: null,
			beibaoBusinessLicenseFile: null,
			toubaoLoading: false,
			beibaoLoading: false,
			rules: {
				customerName: [{ required: true, message: '请选择企业' }],
				certNum: [{ required: true, message: '请输入统一社会信用代码' }],
				address: [{ required: true, message: '请输入详细地址' }],
				// provinceCode: [{ required: true, message: '请选择省份' }],
				cityCode: [{ required: true, message: '请选择地市' }],
				regionCode: [{ required: true, message: '请选择区县' }],
				contactName: [{ required: true, message: '请输入联系人' }],
				contactPhone: [{ required: true, message: '请输入联系方式' }],
				businessLicense: [{ required: true, message: '请上传营业执照' }],
				code: [{ required: true, message: '请输入短信验证码' }]
			},
			customerOptions: [],

			// 保障期限
			qixianForm: {
				startTime,
				endTime: ''
			},
			qixianRules: {
				startTime: { required: true },
				endTime: { required: true }
			},
			qixianLoading: false,

			startDatePickerOptions: {
				disabledDate(date) {
					const start = new Date(startTime)
					return date.getTime() < start.getTime() - 24 * 3600000
				}
			},

			// 地区选择
			areaOptions: {
				provinces: [],
				citys: [],
				regions: []
			},
			pickerOptions: {
				disabledDate(time) {
					const timeStramp = time.getTime()
					const { startTime, endTime } = that.qixianForm
					const minTime = new Date(startTime).getTime()
					const maxTime = new Date(endTime).getTime()
					return minTime > timeStramp && maxTime < timeStramp
				}
			}
		}
	},
	computed: {
		productId() {
			return 11804
		},
		baoxianqijian() {
			var { startTime, endTime } = this.qixianForm
			if (startTime && endTime) {
				var diffTime =
					new Date(endTime).getTime() - new Date(startTime).getTime()
				return Math.floor(diffTime / 1000 / 60 / 60 / 24) + 1
			} else {
				return '--'
			}
		}
	},
	async created() {
		if (this.productId == 11804) {
			this.sameAsToubao = false
			this.$set(this.beibaoForm, 'premiumMode', '')
			this.rules.premiumMode = [{ required: true, message: '请选择行业大类' }]
		}

		var { businessId, policyType } = this.$route.query
		if (businessId) {
			this.fetchBusiness(businessId)
		}
		if (!businessId) {
			var servData = await createBusiness({
				productId: this.productId,
				...UrlSearch
			}).then((res) => res.data)
			businessId = servData.businessId
			policyType = servData.policyType
		}
		this.businessId = businessId
		this.policyType = policyType || 1 // 默认国寿类

		this.fetchCustomerOptions()

		productDetail(this.productId).then((res) => {
			this.productData = res.data

			// 开启录屏
			const channel = 'huanong'
			const oldChannel = localStorage.getItem('channel')

			if (oldChannel !== channel) {
				localStorage.setItem('channel', channel)
				Recorder.renew()
			}
			if (Recorder.status() !== 'living') {
				Recorder.start({
					channel: 'huanong',
					compress: true,
					testServer: 'https://service.aiins.cn/insurance/api/open/putJsonV2'
				})
			}
		})

		queryCitys().then((res) => {
			this.areaOptions.provinces = res.data
		})
	},
	mounted() {},
	watch: {
		sameAsToubao: {
			handler(same) {
				if (same) {
					this.beibaoForm = Object.assign({}, this.toubaoForm)
				}
			},
			immediate: false
		},

		'qixianForm.startTime': {
			handler(val) {
				if (this.productData.policyType === 4) {
					this.qixianForm.endTime = moment(this.qixianForm.startTime)
						.add(1, 'month')
						.date(1)
						.subtract(1, 'days')
						.format('yyyy-MM-DD')
				}
				if (this.productData.insuranceType) {
					var { duration, type } = this.productData.insuranceType
					this.qixianForm.endTime = moment(this.qixianForm.startTime)
						.add(duration, type)
						.subtract(1, 'days')
						.format('yyyy-MM-DD')
				}
			},
			immediate: true
		},
		productData() {
			if (this.productData.policyType === 4) {
				this.qixianForm.endTime = moment(this.qixianForm.startTime)
					.add(1, 'month')
					.date(1)
					.subtract(1, 'days')
					.format('yyyy-MM-DD')
				this.sameAsToubao = false
			}
			if (this.productData.insuranceType) {
				var { duration, type } = this.productData.insuranceType
				this.qixianForm.endTime = moment(this.qixianForm.startTime)
					.add(duration, type)
					.subtract(1, 'days')
					.format('yyyy-MM-DD')
			}
		},
		'productData.insuranceType'(val) {
			var { duration, type } = this.productData.insuranceType
			this.qixianForm.endTime = moment(this.qixianForm.startTime)
				.add(duration, type)
				.subtract(1, 'days')
				.format('yyyy-MM-DD')
		}
	},
	methods: {
		// 获取订单id
		fetchBusiness(businessId) {
			getBusinessById(businessId).then((res) => {
				if (res.data === '您已完成投保') {
					this.$router.replace({
						path: '/insure/pay-success',
						query: this.$route.query
					})
					return
				}
				this.toubaoForm = res.data.customer
				this.beibaoForm = res.data.relation
				this.qixianForm = {
					startTime: res.data.startTime,
					endTime: res.data.endTime
				}
				if (res.data.startTime && res.data.endTime) {
					this.showPerson = true
				}
			})
		},
		// 获取企业选项列表
		fetchCustomerOptions() {
			customerList().then((res) => {
				this.customerOptions = res.data
			})
		},
		// 投保成功回调
		onSuccess() {},
		handleToubaoUpload({ file }) {
			uploadFile({ file, batchId: '' }).then((file) => {
				file.url = file.filePath
				licenseOcr(file).then((res) => {
					this.toubaoForm = Object.assign({}, baoform, res.data)
					this.toubaoForm.businessLicense = file
				})
			})
		},
		handleBeibaoUpload({ file }) {
			uploadFile({ file, batchId: '' }).then((file) => {
				file.url = file.filePath
				licenseOcr(file).then((res) => {
					this.beibaoForm = Object.assign({}, baoform, res.data)
					this.beibaoForm.businessLicense = file
				})
			})
		},
		toubaoBeforeRemove(file, filelist) {
			this.toubaoForm.businessLicense = null
		},
		beibaoBeforeRemove(file, filelist) {
			this.beibaoForm.businessLicense = null
		},
		getBeibaoById(id, type) {
			const isExist = this.customerOptions.find((customer) => {
				return customer.customerId === id
			})
			if (isExist) {
				this.beibaoForm.customerId = id
				customerById(id).then((res) => {
					if (res.data.businessLicense) {
						res.data.businessLicense.url = res.data.businessLicense?.filePath
					}
					this.beibaoForm = Object.assign({}, baoform, res.data)
				})
			} else {
				this.beibaoForm = Object.assign({}, baoform)
				this.beibaoForm.customerName = id
				this.$nextTick(this.$refs.beibaoForm.clearValidate)
			}
		},
		getToubaoById(id) {
			const isExist = this.customerOptions.find((customer) => {
				return customer.customerId === id
			})
			if (isExist) {
				this.beibaoForm.customerId = id
				customerById(id).then((res) => {
					if (res.data.businessLicense) {
						res.data.businessLicense.url = res.data.businessLicense?.filePath
					}
					this.toubaoForm = Object.assign({}, baoform, res.data)
				})
			} else {
				this.toubaoForm = Object.assign({}, baoform)
				this.toubaoForm.customerName = id
				this.$nextTick(this.$refs.toubaoForm.clearValidate)
			}
		},
		sendCode() {
			this.codeLoading = true
			sendSMSCode(this.toubaoForm.contactPhone)
				.then(() => {
					this.$message.success('验证码已发送')
				})
				.finally(() => {
					this.codeLoading = false
				})
		},
		saveToubao() {
			const postData = Object.assign({}, this.toubaoForm)
			postData.businessLicense = postData.businessLicense.fileId
			this.$refs.toubaoForm.validate((valid) => {
				if (valid) {
					this.toubaoLoading = true
					saveInsure(postData, {
						type: 1,
						businessId: this.businessId
					}).finally(() => {
						this.toubaoLoading = false
					})
				}
			})
		},
		saveBeibao() {
			const postData = Object.assign({}, this.beibaoForm)
			postData.businessLicense = postData.businessLicense.fileId
			this.$refs.beibaoForm.validate((valid) => {
				if (valid) {
					this.beibaoLoading = true
					saveBeibao(postData, {
						type: 2,
						businessId: this.businessId
					}).finally(() => {
						this.beibaoLoading = false
					})
				}
			})
		},
		// 保险期限
		saveQixian() {
			this.$refs.qixianForm.validate((valid) => {
				if (valid) {
					this.qixianLoading = true
					saveQixian(this.businessId, this.qixianForm)
						.then(() => {
							this.showPerson = true
						})
						.finally(() => {
							this.qixianLoading = false
						})
				}
			})
		},
		onPreview(url) {
			this.$refs.previewImages.open(url)
		}
	},
	components: { insureImport, XhAddress }
}
</script>

<style lang="scss" scoped="scoped">
.box-card {
	margin-bottom: 20px;
}

.product-name {
	font-size: 20px;
	font-weight: 600;
	text-align: center;
	margin-block: 20px;
}

.import ::v-deep {
	.el-form {
		display: grid;
		gap: 15px;
		grid-template-columns: 1fr 1fr;
	}

	.el-form-item {
		margin-bottom: 0;
	}

	.el-table__header tr th {
		font-size: 13px;
		color: #333;
		background: #fbfcff;
	}

	._error_ {
		color: #f22 !important;
	}
}

.field {
	width: 100%;
}

.append-fix {
	position: absolute;
	right: 1em;
	top: 50%;
	transform: translateY(-50%);
	color: #999;
}

.hide-upload-button ::v-deep .el-upload--picture-card {
	display: none;
}
</style>
